<script setup lang="ts">
import { type FormInstance, Modal } from 'ant-design-vue'
import type { FormState } from '~@/api/role/role'
import { roleSaveApi, roleUpdateApi } from '~@/api/role/role'

const emit = defineEmits(['init'])
const formRef = ref<FormInstance>()
const message = useMessage()
const open = ref(false)

let formState = reactive<FormState>({
  roleId: undefined,
  roleName: '',
  roleCode: '',
  statusFlag: 1,
  remark: '',
  roleSort: 100,
})

function handleUpdate(record?: FormState) {
  formState = record
  open.value = true
}

function handleAdd() {
  formState = {}
  open.value = true
}

/**
 * 新增事件
 *
 */
async function handleOk() {
  if (formState.roleId === undefined) {
    const { data } = await roleSaveApi(formState)
    if (data === 1) {
      message.success('新增成功')
      open.value = false
      Modal.destroyAll()
      emit('init')
    }
    else {
      message.error('新增失败，请重试')
    }
  }
  else {
    const { data } = await roleUpdateApi(formState)
    if (data === 1) {
      message.success('修改成功')
      open.value = false
      Modal.destroyAll()
      emit('init')
    }
    else {
      message.error('修改失败，请重试')
    }
  }
}

function handleCancel() {
  formRef.value?.resetFields()
}

defineExpose({
  handleAdd,
  handleUpdate,
})
</script>

<template>
  <a-modal v-model:open="open" title="用户编辑" width="400px" @ok="handleOk" @cancel="handleCancel">
    <a-form
      ref="formRef"
      :model="formState"
      name="basic"
      :label-col="{ span: 24 }"
      :wrapper-col="{ span: 24 }"
      autocomplete="off"
    >
      <a-form-item
        label="角色名称"
        name="roleName"
        :rules="[{ required: true, message: '请输入角色名称' }]"
      >
        <a-input v-model:value="formState.roleName"/>
      </a-form-item>
      <a-form-item
        label="角色编码"
        name="roleCode"
        :rules="[{ required: true, message: '请输入角色编码' }]"
      >
        <a-input v-model:value="formState.roleCode" />
      </a-form-item>
      <a-form-item
        label="排序"
        name="roleSort"
        :rules="[{ required: true, message: '请输入角色排序' }]"
      >
        <a-input-number v-model:value="formState.roleSort" style="width: 100%" />
      </a-form-item>
      <a-form-item
        label="状态"
        name="statusFlag"
        :rules="[{ required: true, message: '请选择状态' }]"
      >
        <a-select v-model:value="formState.statusFlag" placeholder="请选择状态">
          <a-select-option :value="1">
            启用
          </a-select-option>
          <a-select-option :value="2">
            禁用
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item
        label="备注"
        name="remark"
      >
        <a-textarea v-model:value="formState.remark" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style scoped lang="less">

</style>
